﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Navigation;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using Studio77.CrazyJigsaw.Entities;
using Studio77.CrazyJigsaw.Core;
using Studio77.CrazyJigsaw.Util;

namespace Studio77.CrazyJigsaw.Pages
{
    public partial class GamePage : PhoneApplicationPage
    {
        bool isDraggingTray;
        bool isDraggingPiece;
        double cumulativeDeltaX;
        double cumulativeDeltaY;
        int topmostZIndex;
        List<FrameworkElement> piecesOnTray = new List<FrameworkElement>();
        double trayOffset = 0;
        Random random = new Random(DateTime.Now.Millisecond);
        DispatcherTimer timer = new DispatcherTimer();

        bool isAnswerShowed = false;
        bool isPause = false;
        bool isFinished = false;

        StageData currentStageData;

        List<Image> stars = new List<Image>();

        public GamePage()
        {
            InitializeComponent();
            this.bdrAnswer.MouseLeftButtonDown += new MouseButtonEventHandler(bdrAnswer_MouseLeftButtonDown);
            this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(GamePage_BackKeyPress);
            this.Loaded += new RoutedEventHandler(GamePage_Loaded);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = TimeSpan.FromSeconds(1);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            currentStageData.StageUseSeconds++;
            this.txtGameTime.Text = GetTimeStr(currentStageData.StageUseSeconds);
        }

        void GamePage_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= new RoutedEventHandler(GamePage_Loaded);
            //初始化星星
            foreach (var item in this.stackStars.Children)
            {
                stars.Add((Image)item);
            }
            this.stackStars.Children.Clear();
        }

        void GamePage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            if (!isFinished)
            {
                if (isPause)
                {
                    Continue();
                }
                else
                {
                    PauseGame();
                }
            }
            else
            {
                //游戏完成，不响应返回按钮
            }
        }

        void bdrAnswer_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.StoryboardHideAnswer.Begin();
        }

        void bdrAnswer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (isAnswerShowed)
            {
                this.StoryboardHideAnswer.Begin();
            }
            else
            {
                this.StoryboardShowAnswer.Begin();
            }
            isAnswerShowed = !isAnswerShowed;

        }


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //保存历史数据用的
            base.OnNavigatedFrom(e);

            //保存关卡信息
            StageData stageData = StageManager.Instance.GetCurrentStageData();
            stageData.Points.Clear();
            stageData.Rotates.Clear();
            foreach (FrameworkElement piece in this.PiecesCanvas.Children)
            {
                stageData.Points.Add(new Point(
                  (piece.RenderTransform as CompositeTransform).TranslateX,
                  (piece.RenderTransform as CompositeTransform).TranslateY));
                stageData.Rotates.Add((piece.RenderTransform as CompositeTransform).Rotation);
            }
            StageManager.Instance.StageDatas[StageManager.Instance.LastStage] = stageData;
            StageManager.Instance.SaveStageDatas();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //游戏开始
            base.OnNavigatedTo(e);

            if (!isFinished && !isPause)
            {
                isFinished = false;
                isPause = false;

                string stageCode;
                NavigationContext.QueryString.TryGetValue("StageCode", out stageCode);

                currentStageData = StageManager.Instance.GetCurrentStageData();
                StageManager.Instance.StageDatas[StageManager.Instance.LastStage] = currentStageData;

                RefreshPuzzleImage(stageCode);

                bool arePiecesCorrect = false;

                if (currentStageData.Points.Count == this.PiecesCanvas.Children.Count
                    && currentStageData.Rotates.Count == this.PiecesCanvas.Children.Count)
                {
                    // Restore the persisted position of each piece
                    for (int i = 0; i < this.PiecesCanvas.Children.Count; i++)
                    {
                        UIElement piece = this.PiecesCanvas.Children[i];
                        CompositeTransform t = piece.RenderTransform as CompositeTransform;
                        t.TranslateX = currentStageData.Points[i].X;
                        t.TranslateY = currentStageData.Points[i].Y;
                        t.Rotation = currentStageData.Rotates[i];
                        if (t.TranslateX == 0 && t.TranslateY == 0)
                        {
                            //已经完成了
                            piece.IsHitTestVisible = false;
                        }
                    }
                    arePiecesCorrect = AreAllPiecesCorrect();
                }
                else
                {
                    //开始全新的游戏
                    StartNewGame();
                }

                if (arePiecesCorrect)
                {
                    //ShowAsSolved();
                    StartNewGame();
                }
                else
                {
                    ShowAsUnsolved();
                    this.txtGameTime.Text = GetTimeStr(currentStageData.StageUseSeconds);
                }

                timer.Start();
            }
        }

        private string GetTimeStr(int second)
        {
            return (second / 60).ToString() + "'" + (second % 60).ToString("D2");
        }

        private void StartNewGame()
        {
            DispatcherTimer timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1.5)
            };
            timer.Tick += delegate(object sender, EventArgs args)
            {
                StartOver();
                timer.Stop();
            };
            timer.Start();
        }

        /// <summary>
        /// 开始拖动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void GestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
        {
            // Determine if we're dragging the tray, a piece, or neither
            FrameworkElement source = e.OriginalSource as FrameworkElement;

            if (source == this.Tray)
            {
                // An empty spot on the tray is being dragged
                if (e.Direction == System.Windows.Controls.Orientation.Horizontal)
                    this.isDraggingTray = true;
                return;
            }

            FrameworkElement piece = GetPieceFromDraggedSource(source);
            if (piece == null)
                return;

            if (e.Direction == System.Windows.Controls.Orientation.Horizontal &&
                GetPieceTop(piece) > Constants.ON_TRAY_Y)
            {
                // Although a piece is being dragged, the piece is on the tray and the
                // drag is horizontal, so consider this to be a tray drag instead
                this.isDraggingTray = true;
            }
            else
            {
                SoundManager.PlayEffect(4);

                this.isDraggingPiece = true;
                // A piece is being dragged, so record its pre-drag position
                CompositeTransform t = piece.RenderTransform as CompositeTransform;
                this.cumulativeDeltaX = t.TranslateX;
                this.cumulativeDeltaY = t.TranslateY;
            }
        }

        /// <summary>
        /// 拖动过程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void GestureListener_DragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            //关闭answer界面
            CloseAnswerTip();

            if (this.isDraggingTray)
            {
                // Scroll the tray, 滚动待选条
                ScrollTray(e.HorizontalChange);
            }
            else if (this.isDraggingPiece)
            {
                FrameworkElement piece = GetPieceFromDraggedSource(e.OriginalSource as FrameworkElement);
                if (piece == null)
                {
                    return;
                }

                CompositeTransform t = piece.RenderTransform as CompositeTransform;

                // Apply the position change caused by dragging.
                // We're keeping track of the total change from DragStarted so the piece
                // remains in the right spot after repeated snapping and unsnapping.
                this.cumulativeDeltaX += e.HorizontalChange;
                this.cumulativeDeltaY += e.VerticalChange;
                t.TranslateX = this.cumulativeDeltaX;
                t.TranslateY = this.cumulativeDeltaY;

                // Ensure that this piece is on top of all others
                this.topmostZIndex++;
                Canvas.SetZIndex(piece, this.topmostZIndex);

                // Ensure that the puzzle is no longer in the solved state
                ShowAsUnsolved();

                // If the piece is not on the tray, snap it to a solved horizontal
                // and/or vertical boundary if it's close enough
                double left = GetPieceLeft(piece);
                double top = GetPieceTop(piece);

                if (top > Constants.ON_TRAY_Y)
                    return; // The piece is on the tray, so never mind

                //// Snapping to a horizontal boundary
                //// 处理吸附
                //if (left % Constants.PIECE_WIDTH < Constants.SNAPPING_MARGIN)
                //{
                //    t.TranslateX -= left % Constants.PIECE_WIDTH;
                //}
                //else if (left % Constants.PIECE_WIDTH >
                //           Constants.PIECE_WIDTH - Constants.SNAPPING_MARGIN)
                //{
                //    t.TranslateX += Constants.PIECE_WIDTH - left % Constants.PIECE_WIDTH;
                //}

                //// Snapping to a vertical boundary
                //if (top % Constants.PIECE_HEIGHT < Constants.SNAPPING_MARGIN)
                //{
                //    t.TranslateY -= top % Constants.PIECE_HEIGHT;
                //}
                //else if (top % Constants.PIECE_HEIGHT >
                //           Constants.PIECE_HEIGHT - Constants.SNAPPING_MARGIN)
                //{
                //    t.TranslateY += Constants.PIECE_HEIGHT - top % Constants.PIECE_HEIGHT;
                //}
            }
        }

        private void CloseAnswerTip()
        {
            if (isAnswerShowed)
            {
                this.StoryboardHideAnswer.Begin();
            }
        }

        /// <summary>
        /// 拖动结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void GestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            // Give the tray an extra push (simulating inertia) based on
            // the final dragging horizontal velocity
            if (this.isDraggingTray && e.HorizontalVelocity != 0)
            {
                ScrollTray(e.HorizontalVelocity / 10);
            }
            else
            {
                SetTRAYBlank();
            }

            //处理完成一个单元格的动作
            FrameworkElement piece = GetPieceFromDraggedSource(e.OriginalSource as FrameworkElement);
            if (piece != null && piece is Canvas)
            {
                ProcessCompletePiece(piece);
            }

            this.isDraggingTray = this.isDraggingPiece = false;
        }

        /// <summary>
        /// 判断该块是否完成，完成之后的动画处理
        /// </summary>
        /// <param name="piece"></param>
        private void ProcessCompletePiece(FrameworkElement piece)
        {
            CompositeTransform t = piece.RenderTransform as CompositeTransform;
            if (Math.Abs(t.TranslateX) <= Constants.COMPLETE_PIX && Math.Abs(t.TranslateY) <= Constants.COMPLETE_PIX)
            {
                Canvas.SetZIndex(piece, 0);
                TimeSpan duration = TimeSpan.FromSeconds(0.77);
                piece.IsHitTestVisible = false;
                piece.RenderTransformOrigin = new Point(0.5, 0.5);
                //做个动画
                DoubleAnimation xAnimation = new DoubleAnimation
                {
                    To = 0,
                    Duration = duration,
                    EasingFunction = new QuinticEase()
                };
                DoubleAnimation yAnimation = new DoubleAnimation
                {
                    To = 0,
                    Duration = duration,
                    EasingFunction = new QuinticEase()
                };

                DoubleAnimation scaleXAnimation = new DoubleAnimation
                {
                    From = 1.5,
                    To = 1,
                    Duration = duration,
                    EasingFunction = new BounceEase()
                };
                DoubleAnimation scaleYAnimation = new DoubleAnimation
                {
                    From = 1.5,
                    To = 1,
                    Duration = duration,
                    EasingFunction = new BounceEase()
                };

                DoubleAnimation rotateAnimation = new DoubleAnimation
                {
                    To = 0,
                    Duration = duration,
                    EasingFunction = new QuinticEase()
                };

                Storyboard.SetTargetProperty(scaleXAnimation, new PropertyPath("ScaleX"));
                Storyboard.SetTargetProperty(scaleYAnimation, new PropertyPath("ScaleY"));
                Storyboard.SetTargetProperty(xAnimation, new PropertyPath("TranslateX"));
                Storyboard.SetTargetProperty(yAnimation, new PropertyPath("TranslateY"));
                Storyboard.SetTargetProperty(rotateAnimation, new PropertyPath("Rotation"));
                Storyboard storyboard = new Storyboard();
                Storyboard.SetTarget(storyboard, piece.RenderTransform);
                storyboard.Children.Add(scaleXAnimation);
                storyboard.Children.Add(scaleYAnimation);
                storyboard.Children.Add(xAnimation);
                storyboard.Children.Add(yAnimation);
                storyboard.Children.Add(rotateAnimation);
                storyboard.Completed += (object sender, EventArgs e) =>
                {
                    if (AreAllPiecesCorrect())
                    {
                        ShowAsSolved();
                    }
                };
                storyboard.Begin();
                //播放音效
                SoundManager.PlayEffect(3);
            }
        }

        FrameworkElement GetPieceFromDraggedSource(FrameworkElement source)
        {
            // When a piece is dragged, the source is the path, 
            // but we want to return its parent canvas
            if (source == null || source.Parent == null ||
               (source.Parent as FrameworkElement).Parent == null ||
               (source.Parent as FrameworkElement).Parent != this.PiecesCanvas)
            {
                return null;
            }
            else
            {
                return source.Parent as FrameworkElement;
            }
        }

        double GetPieceTop(FrameworkElement piece)
        {
            return Canvas.GetTop(piece) +
                   (piece.RenderTransform as CompositeTransform).TranslateY;
        }

        double GetPieceLeft(FrameworkElement piece)
        {
            return Canvas.GetLeft(piece) +
                   (piece.RenderTransform as CompositeTransform).TranslateX;
        }

        void ScrollTray(double amount)
        {
            // Retrieve the minimum and maximum horizontal positions among all
            // pieces in the tray, to provide bounds on how far it can scroll
            double minX = double.MaxValue;
            double maxX = double.MinValue;
            this.piecesOnTray.Clear();
            foreach (FrameworkElement piece in this.PiecesCanvas.Children)
            {
                if (GetPieceTop(piece) > Constants.ON_TRAY_Y)
                {
                    this.piecesOnTray.Add(piece);
                    double left = GetPieceLeft(piece);
                    if (left < minX)
                    {
                        minX = left;
                    }
                    if (left > maxX)
                    {
                        maxX = left;
                    }
                }
            }

            if (this.piecesOnTray.Count == 0)
            {
                return;
            }

            // Change the amount if it would make the tray scroll too far
            if (amount < 0 && (maxX + amount < this.ActualWidth -
                Constants.MAX_PIECE_WIDTH || minX < Constants.NEGATIVE_SCROLL_BOUNDARY))
            {
                amount = Math.Max(-maxX + this.ActualWidth - Constants.MAX_PIECE_WIDTH,
                                  Constants.NEGATIVE_SCROLL_BOUNDARY - minX);
            }
            if (amount > 0 && minX + amount > Constants.TRAY_LEFT_MARGIN)
            {
                amount = Constants.TRAY_LEFT_MARGIN - minX;
            }

            // "Scroll" the tray by moving each piece on the tray the same amount
            foreach (FrameworkElement piece in this.piecesOnTray)
            {
                (piece.RenderTransform as CompositeTransform).TranslateX += amount;
            }
            trayOffset += amount;
        }

        private int CompareElementByLeft(FrameworkElement x, FrameworkElement y)
        {
            if (x == null)
            {
                if (y == null)
                {
                    // If x is null and y is null, they're 
                    // equal.  
                    return 0;
                }
                else
                {
                    // If x is null and y is not null, y 
                    // is greater.  
                    return -1;
                }
            }
            else
            {
                if (y == null)
                {
                    return 1;
                }
                else
                {
                    return GetPieceLeft(x).CompareTo(GetPieceLeft(y));
                }
            }
        }

        /// <summary>
        /// 清空空白的备选
        /// </summary>
        void SetTRAYBlank()
        {
            List<FrameworkElement> piecesOnTrayTemp = new List<FrameworkElement>();
            piecesOnTrayTemp.Clear();
            foreach (FrameworkElement piece in this.PiecesCanvas.Children)
            {
                if (GetPieceTop(piece) > Constants.ON_TRAY_Y)
                {
                    piecesOnTrayTemp.Add(piece);
                }
            }
            piecesOnTrayTemp.Sort(CompareElementByLeft);
            //进行缩紧
            for (int i = 0; i < piecesOnTrayTemp.Count; i++)
            {
                UIElement piece = piecesOnTrayTemp[i];
                (piece.RenderTransform as CompositeTransform).TranslateX = i * Constants.TRAY_HORIZONTAL_SPACING - Canvas.GetLeft(piece) + trayOffset;
                (piece.RenderTransform as CompositeTransform).TranslateY = Constants.TRAY_TOP_MARGIN - Canvas.GetTop(piece);
                Canvas.SetZIndex(piece, 0);
            }
            piecesOnTrayTemp.Clear();
        }

        // Move each piece to the tray in a random order
        void StartOver()
        {
            // Copy the children to an array so their order 
            // in the collection is preserved
            UIElement[] pieces = this.PiecesCanvas.Children.ToArray();

            // Shuffle the children in place
            for (int i = pieces.Length - 1; i > 0; i--)
            {
                int r = this.random.Next(0, i);
                // Swap the current child with the randomly-chosen one
                UIElement temp = pieces[i]; pieces[i] = pieces[r]; pieces[r] = temp;
            }

            // Now move the pieces to the bottom in their random order
            for (int i = 0; i < pieces.Length; i++)
            {
                UIElement piece = pieces[i];
                // Alternate the pieces between two rows
                //CreatePieceMovingStoryboard(piece, TimeSpan.Zero, TimeSpan.FromSeconds(1),
                //    (i % 2 * Constants.TRAY_2ND_ROW_HORIZONTAL_OFFSET) +
                //    (i / 2) * Constants.TRAY_HORIZONTAL_SPACING - Canvas.GetLeft(piece),
                //    (i % 2 * Constants.TRAY_VERTICAL_SPACING) + Constants.TRAY_TOP_MARGIN
                //    - Canvas.GetTop(piece)).Begin();

                //旋转角度 -33~33度
                int rotate = random.Next(66) - 33;

                // one row by dave
                CreatePieceMovingStoryboard(piece, TimeSpan.Zero, TimeSpan.FromSeconds(1),
                   i * Constants.TRAY_HORIZONTAL_SPACING - Canvas.GetLeft(piece),
                   Constants.TRAY_TOP_MARGIN - Canvas.GetTop(piece), rotate).Begin();
                // Reset the z-index of each piece
                Canvas.SetZIndex(piece, 0);
                //重置piece的可选中状态
                piece.IsHitTestVisible = true;
            }

            this.topmostZIndex = 0;
            trayOffset = 0;
            ShowAsUnsolved();
            //关闭answer界面
            CloseAnswerTip();
            this.bdrFinish.Visibility = System.Windows.Visibility.Collapsed;
            currentStageData.StageUseSeconds = 0;
            this.txtGameTime.Text = GetTimeStr(currentStageData.StageUseSeconds);
            isPause = false;
            timer.Start();
            isFinished = false;
        }

        // Create a storyboard that animates the piece to the specified position
        Storyboard CreatePieceMovingStoryboard(UIElement piece, TimeSpan beginTime, TimeSpan duration, double finalX, double finalY, double finalRotate)
        {
            DoubleAnimation rotateAnimation = new DoubleAnimation
            {
                To = finalRotate,
                Duration = duration,
                EasingFunction = new QuinticEase()
            };
            DoubleAnimation xAnimation = new DoubleAnimation
            {
                To = finalX,
                Duration = duration,
                EasingFunction = new QuinticEase()
            };
            DoubleAnimation yAnimation = new DoubleAnimation
            {
                To = finalY,
                Duration = duration,
                EasingFunction = new QuinticEase()
            };
            Storyboard.SetTargetProperty(xAnimation, new PropertyPath("TranslateX"));
            Storyboard.SetTargetProperty(yAnimation, new PropertyPath("TranslateY"));
            Storyboard.SetTargetProperty(rotateAnimation, new PropertyPath("Rotation"));

            Storyboard storyboard = new Storyboard { BeginTime = beginTime };
            Storyboard.SetTarget(storyboard, piece.RenderTransform);
            storyboard.Children.Add(xAnimation);
            storyboard.Children.Add(yAnimation);
            storyboard.Children.Add(rotateAnimation);

            return storyboard;
        }

        bool AreAllPiecesCorrect()
        {
            for (int i = 0; i < this.PiecesCanvas.Children.Count; i++)
            {
                UIElement piece = this.PiecesCanvas.Children[i];
                CompositeTransform t = piece.RenderTransform as CompositeTransform;
                if (t.TranslateX != 0 || t.TranslateY != 0)
                    return false; // This piece is in the wrong place
            }
            // All pieces are in the right place
            return true;
        }

        void TestFinish()
        {
            int piecesToMove = 0;
            Storyboard storyboard = null;

            // For any piece that's out of place, animate it to the solved position
            for (int i = 0; i < this.PiecesCanvas.Children.Count; i++)
            {
                UIElement piece = this.PiecesCanvas.Children[i];
                CompositeTransform t = piece.RenderTransform as CompositeTransform;

                if (t.TranslateX == 0 && t.TranslateY == 0)
                {
                    continue; // This piece is already in the right place
                }

                // Animate it to a (0,0) offset, which is its natural position
                storyboard = CreatePieceMovingStoryboard(piece,
                  TimeSpan.FromSeconds(.3 * piecesToMove), // Spread out the animations
                  TimeSpan.FromSeconds(1), 0, 0, 0);
                storyboard.Begin();

                // Ensure each piece moves on top of pieces already in the right place
                this.topmostZIndex++;
                Canvas.SetZIndex(piece, this.topmostZIndex);
                piecesToMove++;
            }

            if (storyboard == null)
            {
                // Everything is in the right place
                this.CompleteImage.Visibility = Visibility.Visible;
            }
            else
            {
                // Delay the showing of CompleteImage until the last storyboard
                // has completed
                storyboard.Completed += delegate(object sender, EventArgs e)
                {
                    this.CompleteImage.Visibility = Visibility.Visible;
                    ShowAsSolved();
                };
            }
        }

        /// <summary>
        /// 显示完成状态
        /// </summary>
        void ShowAsSolved()
        {
            isFinished = true;
            //需要停止定时器
            timer.Stop();


            //显示完成的时间
            this.txtFinishTime.Text = GetTimeStr(currentStageData.StageUseSeconds);
            this.stackStars.Children.Clear();
            this.stackStars.Visibility = System.Windows.Visibility.Collapsed;
            int star = 1;
            if (currentStageData.StageUseSeconds <= 190)
            {
                star = 3;
            }
            else if (currentStageData.StageUseSeconds <= 300)
            {
                star = 2;
            }

            for (int i = 0; i < star; i++)
            {
                this.stackStars.Children.Add(stars[i]);
            }

            if (star > currentStageData.StageLevel)
            {
                currentStageData.StageLevel = star;
            }

            this.StoryboardStarShowing.Begin();
            this.StoryboardStarShowing.Completed += (object s, EventArgs e) =>
            {
                this.stackStars.Visibility = System.Windows.Visibility.Visible;
            };

            this.bdrFinish.Visibility = System.Windows.Visibility.Visible;
            this.CompleteImage.Visibility = Visibility.Visible;

            //播放音效
            SoundManager.PlayEffect(2);
        }

        void ShowAsUnsolved()
        {
            this.CompleteImage.Visibility = Visibility.Collapsed;
        }

        void RefreshPuzzleImage(string stageCode)
        {
            ImageSource imageSource = new BitmapImage(new Uri("/Images/gameImage/" + stageCode + ".jpg", UriKind.Relative));
            if (imageSource != null)
            {
                this.imgAnswer.Source = imageSource;
                this.CompleteImage.Source = imageSource;

                // Each of the 30 pieces needs to be filled with the right image
                foreach (Canvas piece in this.PiecesCanvas.Children)
                {
                    ((piece.Children[0] as Shape).Fill as ImageBrush).ImageSource = imageSource;
                }
            }
        }

        /// <summary>
        /// 暂停
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(1);
            PauseGame();
        }

        /// <summary>
        /// 暂停游戏
        /// </summary>
        private void PauseGame()
        {
            isPause = true;
            timer.Stop();
            this.bdrPause.Visibility = System.Windows.Visibility.Visible;
        }

        /// <summary>
        /// 继续游戏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnContinue_Click(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(1);
            Continue();
        }

        private void Continue()
        {
            isPause = false;
            timer.Start();
            this.bdrPause.Visibility = System.Windows.Visibility.Collapsed;
            //测试
            //TestFinish();
        }

        private void btnRestart_Click(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(1);
            if (MessageBox.Show("Are you sure to restart this photo?", "Restart", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                this.bdrPause.Visibility = System.Windows.Visibility.Collapsed;
                StartOver();
            }
        }

        private void btnMainUI_Click(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(1);
            isFinished = false;

            //跳转到主界面
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void adView1_AdViewEvent(object sender, SmartMad.Ads.WindowsPhone7.WPF.AdViewEventArgs args)
        {

        }

        private void adView1_AdViewFullscreenEvent(object sender, SmartMad.Ads.WindowsPhone7.WPF.AdViewFullscreenEventArgs args)
        {

        }
    }
}